package com.repairService.core.config;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import net.spy.memcached.*;
import net.spy.memcached.auth.AuthDescriptor;
import net.spy.memcached.auth.PlainCallbackHandler;
import net.spy.memcached.spring.MemcachedClientFactoryBean;
import net.spy.memcached.transcoders.SerializingTranscoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MemcachedConfig {

    @Value("${memcache.servers}")
    private String servers;
    @Value("${memcache.username}")
    private String username;
    @Value("${memcache.password}")
    private String password;

    /**
     * 配置memcached
     * @return
     * @throws Exception
     */
    @Bean("memcachedClient")
    public MemcachedClient connectionFactoryBuilder() throws Exception {

        SerializingTranscoder serializingTranscoder = new SerializingTranscoder();
        serializingTranscoder.setCompressionThreshold(1024);

        MemcachedClientFactoryBean memcachedClientFactoryBean = new MemcachedClientFactoryBean();
        memcachedClientFactoryBean.setServers(servers);
        memcachedClientFactoryBean.setProtocol(ConnectionFactoryBuilder.Protocol.BINARY);
        memcachedClientFactoryBean.setTranscoder(serializingTranscoder);
        memcachedClientFactoryBean.setOpTimeout(1000);
        memcachedClientFactoryBean.setTimeoutExceptionThreshold(2000);
        memcachedClientFactoryBean.setHashAlg(DefaultHashAlgorithm.KETAMA_HASH);

        memcachedClientFactoryBean.setLocatorType(ConnectionFactoryBuilder.Locator.CONSISTENT);
        memcachedClientFactoryBean.setFailureMode(FailureMode.Redistribute);
        memcachedClientFactoryBean.setUseNagleAlgorithm(false);
        if (StringUtils.isNotEmpty(username)&&StringUtils.isNotEmpty(password)) {
            PlainCallbackHandler plainCallbackHandler = new PlainCallbackHandler(username,password);
            AuthDescriptor authDescriptor = new AuthDescriptor(new String[]{"PLAIN"},plainCallbackHandler);
            memcachedClientFactoryBean.setAuthDescriptor(authDescriptor);
        }
        memcachedClientFactoryBean.afterPropertiesSet();
        return (MemcachedClient) memcachedClientFactoryBean.getObject();
    }

}
